import { defineStore } from 'pinia'

export const useRunningStore = defineStore('running', {
  state: () => ({
    runningData: {
      totalDays: 28,
      totalDistance: 56.2,
      points: 280
    },
    isCheckedIn: false,
    leaderboard: [
      {
        name: '李明',
        avatar: 'https://randomuser.me/api/portraits/men/2.jpg',
        department: '计算机学院',
        distance: 120.5,
        points: 1205
      },
      {
        name: '王芳',
        avatar: 'https://randomuser.me/api/portraits/women/3.jpg',
        department: '外国语学院',
        distance: 115.8,
        points: 1158
      },
      {
        name: '赵强',
        avatar: 'https://randomuser.me/api/portraits/men/4.jpg',
        department: '体育学院',
        distance: 110.2,
        points: 1102
      },
      {
        name: '张同学',
        avatar: 'https://randomuser.me/api/portraits/men/1.jpg',
        department: '计算机学院',
        distance: 56.2,
        points: 280
      },
      {
        name: '刘华',
        avatar: 'https://randomuser.me/api/portraits/women/5.jpg',
        department: '医学院',
        distance: 45.6,
        points: 230
      }
    ]
  }),
  
  actions: {
    checkIn() {
      if (!this.isCheckedIn) {
        this.isCheckedIn = true
        this.runningData.totalDays++
        const distance = Math.floor(Math.random() * 3) + 2 // 随机生成2-4公里
        this.runningData.totalDistance += distance
        this.runningData.points += distance * 10
        
        // 更新排行榜中自己的数据
        const userIndex = this.leaderboard.findIndex(user => user.name === '张同学')
        if (userIndex !== -1) {
          this.leaderboard[userIndex].distance = this.runningData.totalDistance
          this.leaderboard[userIndex].points = this.runningData.points
        }
        
        // 重新排序排行榜
        this.leaderboard.sort((a, b) => b.points - a.points)
      }
    },
    
    resetCheckInStatus() {
      // 每天重置打卡状态
      this.isCheckedIn = false
    }
  },
  
  getters: {
    currentRank: (state) => {
      const userIndex = state.leaderboard.findIndex(user => user.name === '张同学')
      return userIndex !== -1 ? userIndex + 1 : null
    }
  }
})